// 默认设置
const defaultSettings = {
    defaultDownloader: 'chrome',
    showPopupOnDownload: true,
    rememberLastPath: true,
    lastSavePath: '',
    fileTypeFilters: {
        videoFiles: true,
        audioFiles: true,
        documentFiles: true,
        archiveFiles: true,
        executableFiles: false,
        imageFiles: true,
        otherFiles: true
    },
    safetySettings: {
        enableSafetyCheck: true,
        blockUnsafeDownloads: false
    }
};

// DOM 元素
const elements = {
    defaultDownloader: document.getElementById('defaultDownloader'),
    showPopupOnDownload: document.getElementById('showPopupOnDownload'),
    rememberLastPath: document.getElementById('rememberLastPath'),
    lastSavePath: document.getElementById('lastSavePath'),
    videoFiles: document.getElementById('videoFiles'),
    audioFiles: document.getElementById('audioFiles'),
    documentFiles: document.getElementById('documentFiles'),
    archiveFiles: document.getElementById('archiveFiles'),
    executableFiles: document.getElementById('executableFiles'),
    imageFiles: document.getElementById('imageFiles'),
    otherFiles: document.getElementById('otherFiles'),
    enableSafetyCheck: document.getElementById('enableSafetyCheck'),
    blockUnsafeDownloads: document.getElementById('blockUnsafeDownloads'),
    saveBtn: document.getElementById('saveBtn'),
    resetBtn: document.getElementById('resetBtn'),
    successMessage: document.getElementById('successMessage'),
    errorMessage: document.getElementById('errorMessage')
};

// 加载设置
async function loadSettings() {
    try {
        const result = await chrome.storage.sync.get(['settings']);
        const settings = result.settings || defaultSettings;
        
        // 更新UI
        elements.defaultDownloader.value = settings.defaultDownloader;
        elements.showPopupOnDownload.checked = settings.showPopupOnDownload;
        elements.rememberLastPath.checked = settings.rememberLastPath;
        elements.lastSavePath.value = settings.lastSavePath;
        
        // 文件类型过滤器
        Object.keys(settings.fileTypeFilters).forEach(key => {
            if (elements[key]) {
                elements[key].checked = settings.fileTypeFilters[key];
            }
        });
        
        // 安全设置
        elements.enableSafetyCheck.checked = settings.safetySettings.enableSafetyCheck;
        elements.blockUnsafeDownloads.checked = settings.safetySettings.blockUnsafeDownloads;
        
    } catch (error) {
        showError('加载设置时出错：' + error.message);
    }
}

// 保存设置
async function saveSettings() {
    try {
        const settings = {
            defaultDownloader: elements.defaultDownloader.value,
            showPopupOnDownload: elements.showPopupOnDownload.checked,
            rememberLastPath: elements.rememberLastPath.checked,
            lastSavePath: elements.lastSavePath.value,
            fileTypeFilters: {
                videoFiles: elements.videoFiles.checked,
                audioFiles: elements.audioFiles.checked,
                documentFiles: elements.documentFiles.checked,
                archiveFiles: elements.archiveFiles.checked,
                executableFiles: elements.executableFiles.checked,
                imageFiles: elements.imageFiles.checked,
                otherFiles: elements.otherFiles.checked
            },
            safetySettings: {
                enableSafetyCheck: elements.enableSafetyCheck.checked,
                blockUnsafeDownloads: elements.blockUnsafeDownloads.checked
            }
        };
        
        await chrome.storage.sync.set({ settings });
        showSuccess();
        
        // 通知后台脚本设置已更新
        chrome.runtime.sendMessage({ type: 'settingsUpdated', settings });
        
    } catch (error) {
        showError('保存设置时出错：' + error.message);
    }
}

// 重置设置
async function resetSettings() {
    try {
        await chrome.storage.sync.set({ settings: defaultSettings });
        loadSettings();
        showSuccess('设置已重置为默认值');
    } catch (error) {
        showError('重置设置时出错：' + error.message);
    }
}

// 显示成功消息
function showSuccess(message = '设置已成功保存！') {
    elements.successMessage.textContent = message;
    elements.successMessage.style.display = 'block';
    elements.errorMessage.style.display = 'none';
    
    setTimeout(() => {
        elements.successMessage.style.display = 'none';
    }, 3000);
}

// 显示错误消息
function showError(message) {
    elements.errorMessage.textContent = message;
    elements.errorMessage.style.display = 'block';
    elements.successMessage.style.display = 'none';
    
    setTimeout(() => {
        elements.errorMessage.style.display = 'none';
    }, 5000);
}

// 检查下载器可用性
async function checkDownloaderAvailability() {
    try {
        // 检查迅雷
        const hasThunder = await new Promise(resolve => {
            chrome.runtime.sendNativeMessage('com.xunlei.check', {}, response => {
                resolve(!chrome.runtime.lastError);
            });
        });
        
        // 检查IDM
        const hasIDM = await new Promise(resolve => {
            chrome.runtime.sendNativeMessage('com.idm.check', {}, response => {
                resolve(!chrome.runtime.lastError);
            });
        });
        
        // 更新下载器选项
        const thunderOption = elements.defaultDownloader.querySelector('option[value="thunder"]');
        const idmOption = elements.defaultDownloader.querySelector('option[value="idm"]');
        
        if (thunderOption) {
            thunderOption.disabled = !hasThunder;
            if (!hasThunder) thunderOption.textContent += ' (未安装)';
        }
        
        if (idmOption) {
            idmOption.disabled = !hasIDM;
            if (!hasIDM) idmOption.textContent += ' (未安装)';
        }
        
    } catch (error) {
        console.error('检查下载器可用性时出错：', error);
    }
}

// 事件监听器
document.addEventListener('DOMContentLoaded', () => {
    loadSettings();
    checkDownloaderAvailability();
});

elements.saveBtn.addEventListener('click', saveSettings);
elements.resetBtn.addEventListener('click', resetSettings);

// 自动保存路径相关逻辑
elements.rememberLastPath.addEventListener('change', function() {
    elements.lastSavePath.disabled = !this.checked;
    if (!this.checked) {
        elements.lastSavePath.value = '';
    }
});

// 安全设置联动
elements.enableSafetyCheck.addEventListener('change', function() {
    elements.blockUnsafeDownloads.disabled = !this.checked;
    if (!this.checked) {
        elements.blockUnsafeDownloads.checked = false;
    }
});

// 监听存储变化
chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'sync' && changes.settings) {
        loadSettings();
    }
});